<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button
          v-permissions="{ role: ['ROOT'], permission: ['sys:user:add'] }"
          :icon="Plus"
          type="primary"
          @click="handleEdit($event)"
        >
          添加
        </el-button>
        <el-button :icon="Delete" type="danger" @click="handleDelete($event)">
          批量删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form inline :model="queryForm" @submit.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.title"
              clearable
              placeholder="请输入选题名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="multipleTableRef"
      v-loading="listLoading"
      border
      :data="list"
      :row-class-name="rowClass"
      @row-click="toggleSelection"
      @selection-change="setSelectRows"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection" />
      <el-table-column align="center" label="序号" width="55">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="平台账号"
        prop="platformAccount"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="选题名称"
        prop="title"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="预计完成时间"
        prop="projectTime"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="选题内容"
        prop="details"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="图片"
        prop="pic"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="成本费用"
        prop="fee"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="实际发布时间"
        prop="reportTime"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="汇报状态"
        prop="status"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span>
            {{
              row.status === 1
                ? '选题已完成'
                : row.status === 2
                ? '任务已完成'
                : row.status === 3
                ? '成果已汇报'
                : ''
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="250"
        fixed="right"
      >
        <template #default="{ row }">
          <!--          <el-button-->
          <!--            v-permissions="{ role: ['ROOT'], permission: ['sys:user:edit'] }"-->
          <!--            text-->
          <!--            type="primary"-->
          <!--            :icon="InfoFilled"-->
          <!--            @click="handleDetail(row)"-->
          <!--          >-->
          <!--            详情-->
          <!--          </el-button>-->
          <el-tooltip
            class="box-item"
            effect="dark"
            content="详情"
            placement="top"
          >
            <el-button
              :icon="InfoFilled"
              type="info"
              @click="handleDetail(row)"
            />
          </el-tooltip>
          <!--          <el-button-->
          <!--            v-if="row.status === 1"-->
          <!--            v-permissions="{ role: ['ROOT'], permission: ['sys:user:edit'] }"-->
          <!--            text-->
          <!--            type="primary"-->
          <!--            @click="handleEdit(row, 'informant')"-->
          <!--          >-->
          <!--            填报内容-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            v-else-->
          <!--            v-permissions="{ role: ['ROOT'], permission: ['sys:user:edit'] }"-->
          <!--            text-->
          <!--            type="primary"-->
          <!--            @click="handleEdit(row, 'info')"-->
          <!--          >-->
          <!--            编辑内容-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            v-permissions="{ role: ['ROOT'], permission: ['sys:user:edit'] }"-->
          <!--            text-->
          <!--            type="primary"-->
          <!--            @click="handleEdit(row, 'title')"-->
          <!--          >-->
          <!--            编辑选题-->
          <!--          </el-button>-->
          <el-tooltip
            v-if="row.status === 1"
            class="box-item"
            effect="dark"
            content="填报内容"
            placement="top"
          >
            <el-button
              :icon="DocumentAdd"
              type="success"
              @click="handleEdit(row, 'informant')"
            />
          </el-tooltip>
          <el-tooltip
            v-else
            class="box-item"
            effect="dark"
            content="编辑内容"
            placement="top"
          >
            <el-button
              :icon="EditPen"
              type="success"
              @click="handleEdit(row, 'info')"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑选题"
            placement="top"
          >
            <el-button
              :icon="Edit"
              type="warning"
              @click="handleEdit(row, 'title')"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-button
              v-permissions="{
                role: ['ADMIN'],
                permission: ['sys:user:edit'],
              }"
              :icon="Delete"
              type="danger"
              @click="handleDelete(row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  // import { details, doDelete, getList } from '@/api/userManagement'
  import {
    deleteSelectTopic,
    fetchSelectTopicList,
    fetchSelectTopicDetail,
  } from '@/api/topics'
  // import {
  //   fetchAccountList,
  // } from '@/api/accountManagement'
  // import { getList as fetchRoleList } from '@/api/roleManagement'
  import {
    Delete,
    Plus,
    Search,
    Edit,
    InfoFilled,
    EditPen,
    DocumentAdd,
  } from '@element-plus/icons-vue'
  import { useAclStore } from '@/store/modules/acl'
  export default defineComponent({
    name: 'UserManagement',
    components: {
      Edit: defineAsyncComponent(() => import('./components/Edit')),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const router = useRouter()
      const aclStore = useAclStore()
      const { role, permission } = storeToRefs(aclStore)
      const state = reactive({
        editRef: null,
        roleList: [],
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        selectRow: [], // 选中的行
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          username: '',
        },
        multipleTableRef: null,
      })
      watch(
        () => state.selectRows,
        (val) => {
          // console.log(`新的值是：${newValue}，旧的值是：${oldValue}`)
          state.selectRow = []
          if (val.length > 0) {
            console.log(val, state.selectRows, 1122)
            state.selectRows.forEach((item) => {
              console.log(state.list.indexOf(item), 'state.list.indexOf(item)')
              state.selectRow.push(state.list.indexOf(item))
            })
            console.log(state.selectRows, 'state.selectRows')
          }
        },
        {
          deep: true,
        }
      )
      const rowClass = ({ row, rowIndex }) => {
        if (state.selectRow.includes(rowIndex)) {
          console.log(
            state.selectRow,
            rowIndex,
            row,
            state.selectRow.includes(rowIndex),
            12223
          )
          // console.log(state.selectRow.includes(rowIndex));
          return 'slecleRowColor'
        }
      }
      const toggleSelection = (rows) => {
        if (rows) {
          state.multipleTableRef &&
            state.multipleTableRef.toggleRowSelection(rows, undefined)
        } else {
          // console.log(555,state.selectRow)
          state.multipleTableRef.clearSelection()
        }
      }
      const setSelectRows = (val) => {
        state.selectRows = val
      }
      const handleDetail = (row) => {
        console.log(row, '111')
        router.push(
          `/operaction/reportDetails?id=${row.id}&platformId=${row.platformId}&accountId=${row.accountId}`
        )
      }
      const handleEdit = async (row, types) => {
        try {
          if (row.id) {
            const { data: data } = await fetchSelectTopicDetail({
              assetId: row.id,
            })
            console.log(data, row.status, 'ssss')
            state['editRef'].showEdit(data, row.status, types)
          } else {
            state['editRef'].showEdit()
          }
        } catch (e) {
          console.log(e)
        }
      }

      // const fetchAccount = async () => {
      //   try {
      //     state.listLoading = true
      //     const queryForm = {
      //       pageNum:1,
      //       pageSize:9999,
      //     }
      //     const {
      //       data: { list, total },
      //     } = await fetchAccountList(queryForm)
      //     state.list = list
      //     state.total = total
      //     state.listLoading = false
      //   } catch (e) {
      //     console.log(e)
      //   }
      // }
      const handleDelete = (row) => {
        if (row.id) {
          try {
            $baseConfirm('你确定要删除当前项吗', null, async () => {
              const { msg } = await deleteSelectTopic({ ids: row.id })
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              await fetchData()
            })
          } catch (e) {
            console.log(e)
          }
        } else {
          if (state.selectRows.length > 0) {
            try {
              const ids = state.selectRows.map((item) => item.id).join()
              $baseConfirm('你确定要删除选中项吗', null, async () => {
                const { msg } = await deleteSelectTopic({ ids })
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                await fetchData()
              })
            } catch (e) {
              console.log(e)
            }
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNum = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNum = 1
        fetchData()
      }
      const fetchData = async () => {
        try {
          state.listLoading = true
          const {
            data: { list, total },
          } = await fetchSelectTopicList(state.queryForm)
          state.list = list
          state.total = total
          state.listLoading = false
        } catch (e) {
          console.log(e)
        }
      }
      onMounted(() => {
        fetchData()
        // fetchAccount()
      })

      return {
        ...toRefs(state),
        setSelectRows,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        handleDetail,
        toggleSelection,
        rowClass,
        Delete,
        Plus,
        Search,
        role,
        permission,
        Edit,
        InfoFilled,
        EditPen,
        DocumentAdd,
      }
    },
  })
</script>
<style scoped>
  :deep() .el-table .slecleRowColor {
    background: #eaf4ff !important;
  }

  :deep() .el-table tbody tr:hover > td {
    background-color: #eaf4ff !important;
  }
  :deep() {
    .cell .el-button {
      width: 32px;
    }
  }
</style>
